import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_picker_plus/picker.dart';
import 'package:spendbook/common/widgets.dart';
import 'package:spendbook/models/bankCard.dart';
import 'package:spendbook/models/category.dart';
import 'package:spendbook/models/record.dart';

class AddRecordScreen extends StatefulWidget {
  @override
  _AddRecordScreenState createState() => _AddRecordScreenState();
}

class _AddRecordScreenState extends State<AddRecordScreen> {
  Record record = new Record();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('添加记录'),
        actions: <Widget>[
          TextButton(
            style: Theme.of(context).useMaterial3 ? null : TextButton.styleFrom(foregroundColor: Theme.of(context).colorScheme.onPrimary),
            child: Text(
              '提交',
              style: TextStyle(fontSize: 16),
            ),
            onPressed: () async {
              await record.store();
              Navigator.of(context).pop(record);
            },
          )
        ],
      ),
      body: RecordStatefulWidget(
        record: record,
      ),
    );
  }
}

class ViewRecordScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    Record record = Record()..fromJson(ModalRoute.of(context)!.settings.arguments as Map<String, dynamic>);
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('消费记录'),
      ),
      body: RecordStatefulWidget(record: record, readonly: true),
    );
  }
}

class RecordStatefulWidget extends StatefulWidget {
  RecordStatefulWidget({Key? key, required this.record, this.readonly = false}) : super(key: key);

  final Record record;

  final bool readonly;

  @override
  _RecordStatefulWidgetState createState() => _RecordStatefulWidgetState();
}

class _RecordStatefulWidgetState extends State<RecordStatefulWidget> {
  late Record _record;
  List<String> _chips = [];
  List<BankCard> _cards = [BankCard()..bank = '不选择'];

  @override
  void initState() {
    super.initState();
    _record = widget.record;
    getCategories();
    getCards();
  }

  Future getCategories() async {
    List _list = await Category().fetch();
    setState(() {
      _list.add({'name': '其他'});
      _chips = _list.map<String>((e) => e['name']).toList();
    });
  }

  Future getCards() async {
    List _list = await BankCard().fetch();
    _list.forEach((item) {
      _cards.add(BankCard()..fromJson(item));
    });
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    final cardIndex = _cards.indexWhere((card) => card.id == _record.cardId);
    return PublicList(
      children: <Widget>[
        ListTileScope(
          readonly: widget.readonly,
          title: Row(
            children: <Widget>[
              Expanded(
                child: Text('分类'),
              ),
              Text(_record.category),
            ],
          ),
          trailing: Icon(Icons.chevron_right),
          onTap: () async {
            await Picker(
              selecteds: [_chips.indexOf(_record.category)],
              adapter: PickerDataAdapter(
                pickerData: _chips,
              ),
              confirmText: '确定',
              cancelText: '取消',
              onConfirm: (Picker picker, List value) async {
                setState(() {
                  _record.category = picker.getSelectedValues()[0];
                });
              },
            ).showModal(context);
          },
        ),
        ListTileScope(
          readonly: widget.readonly,
          title: Row(
            children: <Widget>[
              Expanded(
                child: Text('消费金额'),
              ),
              Text(_record.fee.toString()),
              Text('元')
            ],
          ),
          trailing: Icon(Icons.chevron_right),
          onTap: () async {
            final res = await showTextInputDialog(context: context, title: '请输入金额', textFields: [
              DialogTextField(
                  initialText: _record.fee > 0 ? _record.fee.toString() : '',
                  keyboardType: TextInputType.numberWithOptions(decimal: true),
                  validator: (val) => val!.isEmpty || double.tryParse(val) != null ? null : '请输入正确的金额'),
            ]);
            if (res != null) {
              setState(() {
                _record.fee = res.first;
              });
            }
          },
        ),
        ListTileScope(
          readonly: widget.readonly,
          title: Row(
            children: <Widget>[
              Expanded(
                child: Text('扣款来源'),
              ),
              Text(_cards[cardIndex].bank),
            ],
          ),
          trailing: Icon(Icons.chevron_right),
          onTap: () async {
            await Picker(
              selecteds: [cardIndex],
              adapter: PickerDataAdapter(
                pickerData: _cards.map((card) => card.bank).toList(),
              ),
              confirmText: '确定',
              cancelText: '取消',
              onConfirm: (Picker picker, List value) async {
                setState(() {
                  _record.cardId = _cards.firstWhere((card) => card.bank == picker.getSelectedValues()[0]).id;
                });
              },
            ).showModal(context);
          },
        ),
        ListTileScope(
          readonly: widget.readonly,
          title: Row(
            children: <Widget>[
              Expanded(
                child: Text('描述'),
              ),
              Text(_record.description),
            ],
          ),
          trailing: Icon(Icons.chevron_right),
          onTap: () async {
            final res = await showTextInputDialog(context: context, title: '请输入描述', textFields: [
              DialogTextField(initialText: _record.description),
            ]);
            if (res != null) {
              setState(() {
                _record.description = res.first;
              });
            }
          },
        ),
      ],
    );
  }
}
